<template>
  <div class="box section clearfix">
    <el-form :inline="true" style="text-align: left" ref="query" :model="query">
      <el-row class="query">
        <el-form-item label="标题:" prop="title">
          <el-input placeholder="请输入标题" v-model="query.title"></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-select v-model="query.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类:" prop="classify">
          <el-select v-model="query.classify" placeholder="请选择">
            <el-option
              v-for="item in classified"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="btn">
          <el-button type="danger" @click="clearFun" v-no-more-click
            >清空</el-button
          >
          <el-button type="primary" @click="queryFun" v-no-more-click
            >搜索</el-button
          >
        </el-form-item>
        <el-col :span="24">
          <el-form-item>
            <el-button
              icon="el-icon-circle-plus-outline"
              size="small"
              type="primary"
              @click="addNews"
              v-no-more-click
              >添加</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="NewsLists" border stripe style="width: 100%">
      <el-table-column
        label="序号"
        align="center"
        width="180"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="classify"
        label="分类"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.classify == 0">PC端</span>
          <span v-if="scope.row.classify == 1">移动端</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="status"
        label="状态"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.classify == 0">禁用</span>
          <span v-if="scope.row.classify == 1">开启</span>
        </template>
      </el-table-column> -->
      <el-table-column
        prop="createTime"
        label="发布时间"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="editorContent(scope.row)"
            style="color: #ffa42f"
            v-no-more-click
            >编辑</el-button
          >

          <el-popconfirm
            title="确定启用此数据吗？"
            @onConfirm="deleteData(scope.row)"
            v-if="scope.row.status == 0"
          >
            <el-button
              slot="reference"
              type="text"
              size="small"
              style="color: #fb575e"
              v-no-more-click
              >启用</el-button
            >
          </el-popconfirm>
          <el-popconfirm
            title="确定禁用数据吗？"
            @onConfirm="enaConCol(scope.row)"
            v-if="scope.row.status == 1"
          >
            <el-button
              slot="reference"
              type="text"
              size="small"
              style="color: #409eff"
              v-no-more-click
              >禁用</el-button
            >
          </el-popconfirm>
          <el-popconfirm
            title="确定删除此数据吗？"
            @onConfirm="deleteDatas(scope.row)"
          >
            <el-button
              slot="reference"
              type="text"
              size="small"
              style="color: #fb575e"
              v-no-more-click
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <span class="title">小计：共{{ this.total }}条数据</span>
      <el-pagination
        background
        layout="total,prev, pager, next, sizes"
        :total="total"
        :page-size="query.pageSize"
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <div>
        <div class="box1">
          <span class="titleStyle">标题:</span>
          <el-input v-model="form.title" style="width: 300px"></el-input>
        </div>
        <div class="box1">
          <el-form>
            <el-form-item label="分类:" label-width="60px">
              <el-select v-model="form.classify" placeholder="请选择">
                <el-option
                  v-for="item in classified"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="box1">
          <span class="titleStyle">跳转链接:</span>
          <el-input v-model="form.url" style="width: 300px"></el-input>
        </div>
        <div class="box1">
          <el-upload
            class="upload-demo"
            action=""
            ref="uploadImg"
            accept=""
            :multiple="false"
            :http-request="upload"
            :on-change="imgHandlerChange"
            :on-remove="imgHandlerRemove"
            list-type="picture"
            :file-list="imgFileList"
          >
            <el-button size="small" type="primary">封面上传</el-button>
          </el-upload>
        </div>
        <div class="box1">
          <div
            class="edit_wrap"
            v-loading="quillUpdateImg"
            element-loading-text="拼命上传中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
          >
            <!-- 图片上传组件辅助-->
            <el-upload
              class="avatar-uploader"
              action=""
              name="file"
              :headers="header"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :http-request="uploadImg"
              :on-error="uploadError"
              :before-upload="beforeUpload"
            >
            </el-upload>

            <quill-editor
              ref="myQuillEditor"
              v-model="form.content"
              :options="editorOption"
              style="height: 300px"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @change="onEditorChange($event)"
            ></quill-editor>
          </div>
        </div>
      </div>
      <!-- <el-button type="primary" @click="submitData">确 定</el-button> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUplod">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  queryNews,
  NewsCode,
  NewsUplod,
  queryInformation,
  stateSwitch,
  deleteNewss,
} from "../../assets/js/api";

// 富文本!
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import Quill from "quill";
import ImageResize from "quill-image-resize-module"; //调节图片大小
Quill.register("modules/imageResize", ImageResize);

//获取富文本所以图片的id和被删除图片id
const getRemovImgId = (ids, html) => {
  let dom = document.createElement("DIV");
  dom.innerHTML = html;
  const imgDom = dom.getElementsByTagName("img");
  const url = "https://file.xssbdc.com";
  const arr = [];
  for (let i = 0; i < imgDom.length; i++) {
    if (imgDom[i].src.indexOf(url) > -1) {
      let fileName =
        imgDom[i].src.split("/")[imgDom[i].src.split("/").length - 1];
      arr.push(fileName);
    }
  }
  return {
    removeIds: ids,
    imgIds: arr,
  };
};
// import Quill from 'quill'
// import * as Quill from "quill";
// import Treeselect from "@riophae/vue-treeselect";

// let fontSizeStyle = Quill.import("attributors/style/size");
export default {
  data() {
    return {
      imgIds: [], //所有图片id
      removeIds: [], //被删除图片id
      header: {},
      query: {
        title: "", //标题!
        pageNo: 1, //多少页!
        pageSize: 10, //每页多少条数据!
        status: null, //状态!
        classify: null, //分类!
      },
      total: 0, //总数据条数!
      NewsLists: [], //表哥数据存放数组!
      formData: {},
      currentPage: 1,
      dialogVisible: false,
      imgFileList: [],
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      ossUrl: "",
      form: {
        content: "", //新闻内容!
        coverImg: "", //封面图片地址!
        id: null, //id!
        status: 1, //0-禁用 1-启用!
        title: "", //新闻标题!
        classify: null, //分类!
        url: "", //移动端跳转链接!
      },
      params: null,
      options: [
        { value: 0, label: "禁用" },
        { value: 1, label: "开启" },
      ],
      classified: [
        { value: 0, label: "pc端" },
        { value: 1, label: "移动端" },
      ],
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
              ["blockquote", "code-block"], // 引用  代码块
              [{ header: 1 }, { header: 2 }], // 1、2 级标题
              [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
              [{ script: "sub" }, { script: "super" }], // 上标/下标
              [{ indent: "-1" }, { indent: "+1" }], // 缩进
              // [{'direction': 'rtl'}],                         // 文本方向
              [{ size: ["small", false, "large", "huge"] }], // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
              [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
              [{ font: [] }], // 字体种类
              [{ align: [] }], // 对齐方式
              ["clean"], // 清除文本格式
              ["link", "image", "video"], // 链接、图片、视频
            ],
            // container: "#toolbar",
            handlers: {
              image: function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector(".avatar-uploader input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
      },
    };
  },
  components: {
    quillEditor,
  },
  created() {
    this.NewsList();

    let token = localStorage.getItem("token");
    this.header.COOKIE_TOKEN = token;
  },
  methods: {
    onEditorBlur(quill) {
      console.log(quill);
      //失去焦点事件
    },
    onEditorFocus() {
      //获得焦点事件
    },
    onEditorChange({ quill, html, text }) {
      console.log("editor change!", quill);
      console.log("text text!", text);
      console.log("text 11111!", html);
      var int = html;
      console.log(int, "11111111111111111111111111");
      this.$emit("change", html);
      const ids = getRemovImgId(this.imgIds, html);
      this.imgIds = ids.imgIds;
      this.removeIds = ids.removeIds;

      //内容改变事件
    },
    //查询列表数据!
    NewsList() {
      queryNews(this.query).then((res) => {
        this.NewsLists = res.data.records;
        this.total = res.data.total;
        this.currentPage = res.data.current;
      });
    },

    //分页
    handleCurrentChange(cpage) {
      this.query.pageNo = cpage;
      this.NewsList();
    },
    handleSizeChange(psize) {
      this.query.pageSize = psize;
      this.NewsList();
    },
    //清空方法!
    clearFun() {
      this.query.title = "";
      this.query.status = null;
      this.query.classify = null;
      this.NewsList();
    },
    //搜索方法!
    queryFun() {
      this.NewsList();
    },
    // 新增按钮!
    addNews() {
      this.dialogVisible = true;
    },
    // 自定义上传方式!
    upload() {},
    // 图片上传移除的钩子!
    imgHandlerRemove(file, fileList) {
      this.imgFileList = fileList;
      this.form.coverImg = "";
    },
    // 图片改变时的钩子!
    imgHandlerChange(file, fileList) {
      this.imgFileList = fileList;
    },
    // 自定义图片上传!
    async uploadImg(params) {
      var result = "";

      var dataOss = "";
      var suffix = "";
      await NewsCode().then((res) => {
        let imgName = params.file.name;
        suffix = imgName.split(".");

        suffix = suffix[suffix.length - 1];

        let wz = imgName.split(".");
        let imgType = "." + wz[wz.length - 1];
        //创建文件
        let formData = new FormData();
        //上传对象
        dataOss = res.data;
        let ossUrl = dataOss.host;
        formData.append("policy", dataOss.policy);
        formData.append("key", dataOss.dir + dataOss.fileName + imgType);
        formData.append("OSSAccessKeyId", dataOss.accessid);
        formData.append("Signature", dataOss.signature);
        formData.append("success_action_status", 200);
        formData.append("fileName", dataOss.fileName);
        formData.append("file", params.file);
        this.formData = formData;
        this.ossUrl = ossUrl;
      });
      await this.axios
        .post(this.ossUrl, this.formData, this.config)
        .then((res) => {
          if (res.status == 200) {
            result =
              "https://file.xssbdc.com/" +
              dataOss.dir +
              dataOss.fileName +
              "." +
              suffix;
          }
        });

      return result;
    },
    // 提交按钮!
    async uploadToOss(params, fieldName) {
      var dataOss = "";
      var suffix = "";

      await NewsCode().then((res) => {
        let imgName = params.name; //图片全名字!
        suffix = imgName.split(".");

        suffix = suffix[suffix.length - 1]; //图片类型!

        let wz = imgName.split(".");
        let imgType = "." + wz[wz.length - 1];
        //创建文件
        let formData = new FormData();
        //上传对象
        dataOss = res.data;
        let ossUrl = dataOss.host;
        formData.append("policy", dataOss.policy);

        formData.append("key", dataOss.dir + dataOss.fileName + imgType);
        formData.append("OSSAccessKeyId", dataOss.accessid);
        formData.append("Signature", dataOss.signature);
        formData.append("success_action_status", 200);
        formData.append("fileName", dataOss.fileName);
        formData.append("file", params.raw);
        //this.form.contractType = this.uplodType;
        // this.form.showImgSrc=;

        let fileForm = {
          showName: imgName,
          url: dataOss.fileName,
          size: params.size,
          sid: this.id,
          type: this.uplodType,
        };
        console.log(formData, "9999999999");
        this.fileForm = fileForm;
        this.formData = formData;

        this.ossUrl = ossUrl;
      });
      await this.axios
        .post(this.ossUrl, this.formData, this.config)
        .then((res) => {
          if (res.status == 200) {
            this.form[fieldName] =
              "https://file.xssbdc.com/" +
              dataOss.dir +
              dataOss.fileName +
              "." +
              suffix;
          }
        });
    },
    async submitData() {
      //表头信息
      /* let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }; */
      if (this.imgFileList.length > 0 && this.form.coverImg == "") {
        await this.uploadToOss(this.imgFileList[0], "coverImg");
      }
      if (this.form.classify == 1) {
        if (
          this.form.content == "" ||
          this.form.coverImg == "" ||
          this.form.title == "" ||
          this.form.url == ""
        ) {
          this.$message({ message: "请先完善信息", type: "error" });
          return;
        }
      }
      if (
        this.form.content == "" ||
        this.form.coverImg == "" ||
        this.form.title == "" ||
        this.form.classify == null
        // this.form.url == ""
      ) {
        this.$message({ message: "请先完善信息", type: "error" });
        return;
      } else {
        NewsUplod(this.form).then((data) => {
          if (data.code == 200) {
            this.$message({ message: data.message, type: "success" });
            this.cancelUplod();
            this.NewsList();
          } else {
            this.$message({ message: data.message, type: "error" });
          }
        });
      }
      // if (
      //   this.form.content == "" ||
      //   this.form.coverImg == "" ||
      //   this.form.title == "" ||
      //   this.form.classify == null
      // ) {
      //   this.$message({ message: "请先完善信息", type: "error" });
      //   return;
      // } else {
      //   NewsUplod(this.form).then((data) => {
      //     if (data.code == 200) {
      //       this.$message({ message: data.message, type: "success" });
      //       this.cancelUplod();
      //       this.NewsList();
      //     } else {
      //       this.$message({ message: data.message, type: "error" });
      //     }
      //   });
      // }
    },
    //取消按钮!
    cancelUplod() {
      this.$refs.uploadImg.clearFiles();
      this.dialogVisible = false;
      this.form.content = "";
      this.form.coverImg = "";
      this.form.id = null;
      this.form.url = "";
      this.form.status = 1;
      this.form.title = "";
      this.imgFileList = [];
      this.params = null;
      this.form.classify = null;
    },
    handleClose() {
      this.cancelUplod();
    },
    // 富文本图片上传前
    beforeUpload() {
      // 显示loading动画
      this.quillUpdateImg = true;
    },
    uploadError() {
      // loading动画消失
      this.quillUpdateImg = false;
      this.$message.error("图片插入失败");
    },
    uploadSuccess(res) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.url为服务器返回的图片地址
        quill.insertEmbed(length, "image", res);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      // loading动画消失
      this.quillUpdateImg = false;
      this.NewsList();
    },
    // 编辑按钮!
    editorContent(data) {
      queryInformation(data.id).then((res) => {
        if (res.code == 200) {
          this.dialogVisible = true;
          this.form.content = res.data.content;
          this.form.coverImg = res.data.coverImg;
          this.form.classify = res.data.classify;
          this.imgFileList.push({
            name: res.data.coverImg.split("/")[
              res.data.coverImg.split("/").length - 1
            ],
            url: res.data.coverImg,
          });

          this.form.id = res.data.id;
          this.form.title = res.data.title;
          this.form.url = res.data.url;
        }
      });
    },
    // 禁用按钮!
    enaConCol(data) {
      stateSwitch({ id: data.id, status: 0 }).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.NewsList();
        } else {
          this.$message.error(res.message);
        }
        this.NewsList();
      });
    },
    deleteData(data) {
      stateSwitch({ id: data.id, status: 1 }).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.NewsList();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    deleteDatas(data) {
      var id = data.id;

      deleteNewss(id).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.NewsList();
        } else {
          this.$message.error(res.message);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
::v-deep .el-pagination {
  position: absolute;
  right: 0;
  margin-top: 20px;
}
::v-deep .el-pagination__total {
  visibility: hidden;
}
.title {
  font-family: Microsoft YaHei;
  font-size: 12px;
  font-weight: 400;
  line-height: 21px;
  position: absolute;
  left: 0;
  margin-top: 15px;
  color: rgba(51, 51, 51, 1);
}
.box1 {
  margin-bottom: 10px;
  text-align: left;
}
/deep/ .el-dialog__footer {
  margin-top: 60px;
}
.titleStyle {
  display: inline-block;
  width: 60px;
  text-align: right;
}
</style>